package cn.wolfcode.service.Impl;

import cn.hutool.core.util.RandomUtil;
import cn.wolfcode.domain.Answer;
import cn.wolfcode.domain.Exam;
import cn.wolfcode.domain.ExamQuestion;
import cn.wolfcode.domain.Question;
import cn.wolfcode.mapper.ExamMapper;
import cn.wolfcode.mapper.ExamQuestionMapper;
import cn.wolfcode.mapper.QuestionMapper;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IExamService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

@Service
public class ExamServiceImpl implements IExamService {

    @Autowired
    private ExamMapper examMapper;

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private ExamQuestionMapper examQuestionMapper;

    @Override
    public void save(Exam exam) {
        int i=1;
        examMapper.insert(exam);
        Long id = exam.getId();
        List<Question>questionList=questionMapper.selectByTypeId(1);
        Set<Question> questions = RandomUtil.randomEleSet(questionList, exam.getSingleNumber());
        for (Question question : questions) {
            examQuestionMapper.insert(new ExamQuestion(id,question.getId(),i,exam.getSingleScore()));
                i++;
        }

        List<Question> multipleList = questionMapper.selectByTypeId(2);
        Set<Question> multipleQuestions = RandomUtil.randomEleSet(multipleList, exam.getMultipleNumber());
        for (Question multipleQuestion : multipleQuestions) {
            examQuestionMapper.insert(new ExamQuestion(id,multipleQuestion.getId(),i,exam.getMultipleScore()));
            i++;
        }
        List<Question> judgeList  = questionMapper.selectByTypeId(3);
        Set<Question> judgeQuestions  = RandomUtil.randomEleSet(judgeList, exam.getJudgeNumber());
        for (Question judgeQuestion : judgeQuestions) {
            examQuestionMapper.insert(new ExamQuestion(id,judgeQuestion.getId(),i,exam.getJudgeScore()));
            i++;
        }

    }


    @Override
    public void delete(Long id) {
        examMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void update(Exam exam) {
        examMapper.updateByPrimaryKey(exam);
    }

    @Override
    public Exam get(Long id) {
        return examMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Exam> listAll() {
        return examMapper.selectAll();
    }

    @Override
    public PageInfo<Exam> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize()); //对下一句sql进行自动分页
        List<Exam> exams = examMapper.selectForList(qo); //里面不需要自己写limit
        return new PageInfo<Exam>(exams);
    }

    @Override
    public List<Answer> selectByItemId(Long id) {
        return examMapper.selectByItemId(id);
    }
}
